package com.dabaozhan.modules.wx_app.controller;

import com.alibaba.fastjson.JSON;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.Constants;
import com.dabaozhan.common.utils.Utils;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.CardEntity;
import com.dabaozhan.modules.wx_app.entity.PayPassEntity;
import com.dabaozhan.modules.wx_app.entity.SmsEntity;
import com.dabaozhan.modules.wx_app.entity.UserEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.service.CardService;
import com.dabaozhan.modules.wx_app.service.PayPassService;
import com.dabaozhan.modules.wx_app.service.SmsService;
import com.dabaozhan.modules.wx_app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author houzhong
 * @date 2019-01-10 18:40
 */
@Api(value = "设置支付密码", description = "设置支付密码")
@RestController
@RequestMapping("/wx_app")
public class PayPassController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private PayPassService payPassService;

    /**短信*/
    @Autowired
    private SmsService smsService;

    /**用户*/
    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询是否设置支付密码")
    @RequestMapping(value = "/payPassInfo")
    public String payPassInfo(String userId) {
        ResponseDto<PayPassEntity> responseDto = new ResponseDto<PayPassEntity>();
        try {
            PayPassEntity v = payPassService.findByPayUserId(userId);
            if (v != null) {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(v);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_400);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("查询是否设置支付密码发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("查询是否设置支付密码发生异常:{}-返回结果:{}", JSON.toJSONString(userId),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "设置支付密码校验")
    @RequestMapping("/checkPay")
    public String checkPay(UserEntity v,String code) throws Exception {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            UserEntity user = userService.findByCardUserId(v.getId());
            if (user != null) {
                SmsEntity sms = new SmsEntity();
                sms.setPhone(v.getTelephone());
                sms.setStatus(2);
                List<SmsEntity> smsVo = smsService.findPhone(sms);
                if (smsVo.size() > 0) {
                    if (user.getCardName().equals(v.getCardName())
                            && user.getCardNum().equals(v.getCardNum())
                            && user.getTelephone().equals(v.getTelephone())) {
                        if (!smsVo.get(smsVo.size()-1).getCode().equals(code)) {
                            //验证码错误
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_201);
                        }else if (!smsVo.get(smsVo.size()-1).getPhone().equals(v.getTelephone())) {
                            //短信手机号错误
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_202);
                        }else {
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                        }
                    }else {
                        //信息错误
                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_207);
                    }
                }else {
                    //验证码不存在
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_203);
                }
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("设置支付密码校验发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("设置支付密码校验发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "新增/忘记支付密码")
    @RequestMapping("/setPay")
    public String setPay(PayPassEntity v) {
        ResponseDto<PayPassEntity> responseDto = new ResponseDto<PayPassEntity>();
        try {
            PayPassEntity  passVo = payPassService.findByPayUserId(v.getUserId());
            if (passVo != null) {
                if (passVo.getUserId().equals(v.getUserId())) {
                    passVo.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
                    payPassService.updatePayPass(passVo);
                }
            }else {
                v.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
                payPassService.savePayPass(v);
            }
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
            responseDto.setResult(v);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("新增/忘记支付密码发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("新增/忘记支付密码发生异常:{}-返回结果:{}", JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "校验支付密码是否正确")
    @RequestMapping("/checkPayPad")
    public String checkPayPad(PayPassEntity v) {
        ResponseDto<String> responseDto = new ResponseDto<String>();
        try {
            PayPassEntity  passVo = payPassService.findByPayUserId(v.getUserId());
            if (passVo != null) {
                String password = Utils.md5(v.getPwdPass(), Constants.PAY_PASS_CACHE_KEY);
                if (passVo.getPassword().equals(password)) {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_501);
                }
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("校验支付密码是否正确发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("校验支付密码是否正确发生异常:{}-返回结果:{}", JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "修改支付密码")
    @RequestMapping("/setUpdatePay")
    public String setUpdatePay(PayPassEntity v) {
        ResponseDto<PayPassEntity> responseDto = new ResponseDto<PayPassEntity>();
        PayPassEntity  passVo = payPassService.findByPayUserId(v.getUserId());
        if (passVo != null) {
            String password = Utils.md5(v.getPwdPass(), Constants.PAY_PASS_CACHE_KEY);
            if (passVo.getPassword().equals(password)) {
                passVo.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
                payPassService.updatePayPass(passVo);
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(v);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_501);
            }
        }
        return JSON.toJSONString(responseDto);
    }
}
